const ProgressBar = require('progress')
const chalk = require('chalk')

module.exports = async (repeatTimes, classItem, page) => {
  for (let index = 0; index < repeatTimes; index++) {
    if (classItem.time < classItem.total) {
      console.log()
      console.log(`${classItem.name} 课程还差${classItem.total-classItem.time}分钟，开始刷课，刷${repeatTimes}遍`)

      // 该课程未完成，开始刷课
      await page.goto(classItem.href, {
        waitUntil: 'networkidle',
      });
      await page.waitForTimeout(2000)
      await page.click('#tmenu a[title="课程学习"]')
      await page.waitForSelector('#menu ul li:nth-child(3)')
      await page.click('#menu ul li:nth-child(3)')

      await page.waitForSelector('#mainFrame')

      const frame = page.frames().find((frame) => {
        return frame.name() === 'mainFrame'
      });

      let needstar = []
      let le3 = await page.$('#menu ul li:nth-child(3) .leve2 li a')
      if (le3) {
        // le3存在，说明是马克思主义基本原理的课程，这个课程有些奇怪，单独处理
        needstar = await page.$$eval('#menu ul li:nth-child(3) .leve2 li a', (element) => {
          console.log('element===>', element)
          return element.map((item, index) => {
            return {
              name: item.querySelector('span').textContent.replace(/\s/g, ''),
              href: item.href
            }
          })
        });
      } else {
        await page.waitForTimeout(1000)
        await frame.waitForSelector('table tbody tr td:not(.align_c)')

        needstar = await frame.$$eval('table tbody tr td:not(.align_c)', (element) => {
          return element.map((item, index) => {
            return {
              name: item.textContent.replace(/\s/g, ''),
              href: item.parentElement.querySelector('td.align_c a').href
            }
          })
        });
      }

      // needstar.length = 5

      for (const item of needstar) {
        console.log()
        console.log(`尝试播放${item.name}`)
        const u = await page.goto(item.href, {
          waitUntil: 'networkidle',
        }).catch(() => {
          // 链接超时，跳过当前循环
          // console.log(chalk.red('连接超时，跳过当前章节，进入下一章'))
          // return 0
        })
        // if(u===0){
        //   continue;
        // }
        await page.waitForTimeout(1000)

        const video = await page.$('video')

        if (video) {
          console.log('已检测到视频，每个视频播放10分钟，时间到会自动切换到下一个视频')
          console.log(chalk.green('当前视频正在播放...'))
          // page.on('request',(request)=>{
          //   console.log('请求start', request.postData(), request.url(), 'end')
          // })
          await new Promise((resolve, reject) => {
            const bar = new ProgressBar('  播放中 [:bar] :percent 剩余:etas', {
              complete: '=',
              incomplete: ' ',
              width: 30,
              total: 10 * 60,
              // total: 30
            });

            const timer = setInterval(function () {
              bar.tick();
              if (bar.complete) {
                resolve()
                clearInterval(timer);
              }
            }, 1000);
          })
        } else {
          console.log('没有检测到视频，直接进入下一周')
        }
      }
    }
  }
}